<template>
  <div class="login-wrap">
    <el-card class="login-container">
      <div class="login-title" slot="header">个人博客后台管理系统</div>
      <el-form ref="loginform" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="用户名" prop="username">
          <el-input
            v-model="form.username"
            placeholder="请输入用户名"
          ></el-input>
        </el-form-item>
        <el-form-item label="密 码" prop="password">
          <el-input
            v-model="form.password"
            placeholder="请输入密码"
            show-password
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="login">登入</el-button>
          <el-button>重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
export default {
  name: 'Login',
  data() {
    return {
      form: {
        username: '',
        password: '',
      },
      rules: {
        username: [
          {
            required: true,
            message: '用户名不能为空',
            tigger: 'blur',
          },
        ],
        password: [
          {
            required: true,
            message: '密码不能为空',
            tigger: 'blur',
          },
        ],
      },
    };
  },
  methods: {
    login() {
      //校验表单  ref属性
      // 通过this.$refs['loginform']，拿到form组件对象    validate方法
      this.$refs['loginform'].validate((valid) => {
        //valid为true:表单通过
        if (valid) {
          //发送post请求,比对用户名和密码
          this.$http.get('/users').then((data) => {
            const arrs = data.result.data;
            const username = this.form.username;
            const password = this.form.password;
            console.log(arrs[1].username);

            for (let i = 0; i < arrs.length; i++) {
              if (
                (username == arrs[i].username) &
                (password == arrs[i].password)
              ) {
                this.$message({
                  message: '登入成功',
                  type: 'success',
                });
                //跳转到 后台首页
                //编程式导航
                this.$router.push('./dashboard');
              }

              break;
            }
          });

          // //提示登入成功
          // localStorage.setItem('isLogin', 1);
          // this.$message({
          //   message: '登入成功',
          //   type: 'success',
          // });
          //跳转到 后台首页
          //编程式导航
          // this.$router.push('./dashboard');
        } else {
          //提示框
        }
      });
    },
  },
};
</script>

<style>
.login-wrap {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  background-color: skyblue;
}
.login-container {
  width: 400px;
  /* height: 200px; */
  background-color: #fff;
}
.login-title {
  /* 居中 */
  text-align: center;
}
</style>
